package com.violet.gateway.utils;

import cn.hutool.json.JSONUtil;
import com.violet.common.response.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @author admin
 */
public class WebfluxResponseUtil {

    public static Mono<Void> responseWrite(ServerWebExchange exchange, HttpStatus httpStatus, Result<Void> result) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(httpStatus);
        response.getHeaders().set("Content-Type", "application/json; charset=utf-8");
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(JSONUtil.toJsonStr(result).getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer)).doOnError((error) -> {
            DataBufferUtils.release(buffer);
        });
    }


    public static Mono<Void> responseFailed(ServerWebExchange exchange, HttpStatus httpStatus, String msg) {
        Result<Void> result = Result.failure(msg);
        return responseWrite(exchange, httpStatus, result);
    }

}